package gameadminlogic

import (
	"context"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/game"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"

	"navi-mumbai/app/rpc/game/internal/svc"
	"navi-mumbai/app/rpc/game/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetGameListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetGameListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetGameListLogic {
	return &GetGameListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 获取游戏列表
func (l *GetGameListLogic) GetGameList(in *pb.GetGameListReq) (*pb.GetGameListResp, error) {
	defer utils.RecoverPanic()

	var gameList []*game.Game
	var err error
	gameList, err = l.svcCtx.GameModel.Find(l.ctx, in.ProviderId, in.State, in.PageNo, in.PageSize)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}

	var resp pb.GetGameListResp
	resp.List = make([]*pb.Game, 0)
	if len(gameList) == 0 {
		return &resp, nil
	}

	// 获取数量
	if in.PageNo <= 1 {
		resp.Total, err = l.svcCtx.GameModel.Count(l.ctx, in.ProviderId, in.State)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return &resp, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		}
	}

	//
	for i := 0; i < len(gameList); i++ {
		var gameInfo pb.Game
		gameInfo.GameId = gameList[i].GameId
		gameInfo.GameName = gameList[i].GameName
		gameInfo.GameType = gameList[i].GameType
		gameInfo.GGameId = gameList[i].ProviderGameId
		gameInfo.GameLogo = gameList[i].GameLogo
		gameInfo.ProviderId = gameList[i].ProviderId
		gameInfo.GameUrl = gameList[i].GameUrl
		gameInfo.InstantId = gameList[i].InstantId
		gameInfo.State = gameList[i].State
		gameInfo.CreateTime = gameList[i].CreateTime.Format(dbkey.DateTimeCNFormat)
		resp.List = append(resp.List, &gameInfo)
	}

	return &resp, nil
}
